<?php
declare (strict_types = 1);
namespace app\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\captcha\facade\Captcha;

//Token管理类
class Token{
    public function index(){

    }

    public function verify(){
        return Captcha::create();
    }

    //token验证
    public function check_token($token){
        if(empty($token)) return ["code"=>0,'msg'=>'token 无效!'];

        //查找加明商
        $user = Db::table('user')->where('token',$token)->find();
        if(!empty($user)){
            if(time()-$user['time_out']>1){
                return ["code"=>0,'msg'=>'token长时间未使用而过期，需重新登陆!'];
            }

            $cust = Db::table('customer')->where('mobile',$user['mobile'])->find();
            return ["code"=>1,"type"=>3,"customer"=>$cust,"msg"=>"加盟商登录!"];
        }

        //查找学员
        $cust = Db::table('customer')->where('token',$token)->find();
        if(!empty($cust)){
            if(time()-$cust['time_out']>1){
                return ["code"=>0,'msg'=>'token长时间未使用而过期，需重新登陆!'];
            }

            return ["code"=>1,"type"=>$cust['type'],"customer"=>$cust,"msg"=>$cust['type']==2?"教练登录":"学员登录!"];
        }
        
        return ['code'=>0,'msg'=>"token验证失败!"];
    }


    public function make_token($str=''){
        return  sha1(md5(time()."x")); 
    }

    public function update_token($table,$id){
        if(empty($table) || empty($id)) return false;

        $new_time_out = time() + 604800; //604800是七天
        $token = $this->make_token();         
        $table_arr = array(
            'id'=>$id,
            'token'=>$token,
            'time_out'=>$new_time_out
         );

        $res =Db::table($table)->update($table_arr);
        if($res){
            return true;
        }
        return false;

    }



}
